//
//  GChatViewController.m
//  SouthChina
//  群聊主页面
//  Created by zorro on 15/6/22.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "GChatViewController.h"
#import "MessageSessionDao.h"
#import "MessageSession.h"
#import "Contact.h"
#import "ContactDao.h"
#import "MessageSessionCell.h"
#import "FriendVerifyViewController.h"
#import "GroupTableViewCell.h"
#import "SDRefresh.h"
#import "GroupInfoViewController.h"
#import "CreateGroupViewController.h"
#import "selectMemberViewController.h"
#import "PersonalCenterTableViewCell.h"
#import "ZbarReaderViewController.h"
#import "SearchGroupViewController.h"



@interface GChatViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    NSMutableArray * groupData;         //我的群数据
    NSMutableArray * chatData;          //我的讨论组
    NSArray *sTitls;
    NSArray *sPics;
    NSInteger pageSize;
}
@end

@implementation GChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    pageSize = 10;
    sTitls = @[@"创建群组",@"创建讨论组",@"扫一扫进群"];
    sPics = @[@"creategroup.png",@"creategroup.png",@"pic_scan.png"];
    
    groupData = [[NSMutableArray alloc]init];
    chatData = [[NSMutableArray alloc]init];
    if([_GChatType isEqualToString:@"5"])
        [self addTitleBarWithBackBtn:@"群组" needReturn:YES];
    else
        [self addTitleBarWithBackBtn:@"讨论组" needReturn:YES];
    
    UIView * bodyView = [[[NSBundle mainBundle] loadNibNamed:@"GroupChatView" owner:self options:nil] objectAtIndex:0];
    bodyView.frame = (CGRect){0, self.titlebar.frame.origin.y+self.titlebar.frame.size.height,  SCREEN_WIDTH, SCREEN_HEIGHT-self.titlebar.frame.size.height};
    [self.view addSubview:bodyView];
    
    //导航栏上面的+号按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(258.0f, (YNEW), 60.0f, 40.0f);
    [rightBtn addTarget:self action:@selector(showRightBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"addfriend_group_flag"] forState:UIControlStateNormal];
   // rightBtn.imageEdgeInsets = UIEdgeInsetsMake ( 5 ,  10 , 5 , 10 );
    
    [self.titlebar addSubview:rightBtn];
    
    _tabGroup.delegate = self;
    _tabGroup.dataSource = self;
   // _tabGroup.backgroundColor =[UIColor whiteColor];
   
    
    //如果是讨论组
    if([_GChatType isEqualToString:@"4"])
    {
        _tabGroup.tag = GCHATTYPE_CHAT;
        [self refreshChatTableView];
    }
    else
    {
         _tabGroup.tag = GCHATTYPE_MY;
         [self refreshTableView];
    }
    
    //搜索框
    _searchGroup.showsCancelButton=NO;
    _searchGroup.barStyle=UIBarStyleDefault;
    _searchGroup.placeholder = @"";
    _searchGroup.delegate =self;
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"搜索框的点击事件");
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //跳转到通讯录通用搜索页面
    SearchGroupViewController * searchgroup =[[SearchGroupViewController alloc] initWithNibName:nil bundle:nil];
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:searchgroup animated:YES];
    return  NO;//返回NO不显示键盘
}

-(void)showRightBtnView:(id)sender
{
    CGFloat xWidth = self.view.bounds.size.width - 162.0f;
    CGFloat yHeight = 120.0f;
    UIPopoverListView *poplistview = [[UIPopoverListView alloc] initWithFrame:CGRectMake(0, 0, xWidth, yHeight)];
    poplistview.delegate = self;
    poplistview.datasource = self;
    poplistview.listView.scrollEnabled = YES;
    poplistview.center = CGPointMake(240,130);
    [poplistview show];
    
}

#pragma mark - UIPopoverListViewDataSource

- (UITableViewCell *)popoverListView:(UIPopoverListView *)popoverListView
                    cellForIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"PersonalCenterTableViewCell";
    PersonalCenterTableViewCell *cell = [[PersonalCenterTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    
    UIImageView *cellimage =  [[UIImageView alloc] initWithFrame:CGRectMake(15, 10,20, 20)];
    UILabel * titlaLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 10, 100, 20)];
    titlaLabel.text = sTitls[indexPath.row];
    cellimage.image = [UIImage imageNamed:sPics[indexPath.row]];
    [cell addSubview:cellimage];
    
    titlaLabel.textColor = [UIColor colorWithRed:85.0f/255.0f green:85.0f/255.0f blue:85.0f/255.0f alpha:1.0f];
    titlaLabel.textAlignment = NSTextAlignmentLeft;
    titlaLabel.font = [UIFont systemFontOfSize:12.0f];
    [cell addSubview:titlaLabel];
    
    return cell;
}

- (NSInteger)popoverListView:(UIPopoverListView *)popoverListView
       numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

#pragma mark - UIPopoverListViewDelegate
- (void)popoverListView:(UIPopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row==0)//创建群组
    {
        CreateGroupViewController * groupCreate = [[CreateGroupViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:groupCreate animated:NO];
    }
    if(indexPath.row == 1) //创建讨论组
    {
        selectMemberViewController * chatCreate = [[selectMemberViewController alloc] init];
        NSMutableSet *selectedContact = [[NSMutableSet alloc]init];
        
        //讨论组首先有自己20151010
        /*
        NSString *swheresql = [NSString stringWithFormat:@"SELECT *,count(distinct id) from contacts where operate='U' and id='%@' group by id ",[DE getGlobalVar:LOGIN_USER_ID]];
        NSLog(@"用户id :%@",[DE getGlobalVar:LOGIN_USER_ID]);
      
        NSMutableArray *allList  = [[NSMutableArray alloc] initWithArray:[ContactDao getDistinctContactByWhere:swheresql]];
          NSLog(@"%d",allList.count);
        Contact *contact =allList[0];
        [selectedContact addObject:contact];
        */
        
        chatCreate.selectedContact = selectedContact;
        chatCreate.CreateType =CREATETYPE_CREATECHAT;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:chatCreate animated:NO];
    }
    if(indexPath.row == 2)
    {
        ZbarReaderViewController * scanning = [[ZbarReaderViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:scanning animated:NO];
    }
   
}
- (CGFloat)popoverListView:(UIPopoverListView *)popoverListView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0f;
}

/*
-(void) refreshGChatTableView:(UITableView *)tab arrayData:(NSMutableArray *)arrayData key:(NSString*) key pageNo:(NSInteger*) pageNo  FooterView:(SDRefreshFooterView*)footerView
{
    NSDictionary *map = @{@"groupType":_GChatType,@"groupName":key,@"pageNo": [NSString stringWithFormat:@"%ld",(long)*pageNo],@"pageSize":[NSString stringWithFormat:@"%ld",(long)pageSize]};
    
    //如果上次现实加载提示窗还没清除，又进行了调用，界面出现多个提示框，清理时会出异常，导致无法全部清理干净，界面僵死
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"searchGrp" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success)
        {
            NSArray *array =  [data objectForKey:@"grps"];
            if([array count] >0)
            {
                (*pageNo)++;
                [arrayData addObjectsFromArray:array];
                [tab reloadData];
            }
        }
        else{
            [self showAlerHUD:@"获取群列表失败"];
        }
        
        [footerView endRefreshing];
    }];
}
*/

-(void) refreshTableView
{
    NSMutableArray *array  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Group' and operate='U'"]];
    
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"mHAS_CHILD== %@", @"1"];
    NSArray *MyAPP = [array filteredArrayUsingPredicate:predicate1];
    
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"mHAS_CHILD== %@", @"0"];
    NSArray *NoMyAPP = [array filteredArrayUsingPredicate:predicate2];
    
    groupData = [[NSMutableArray alloc]init];
    if(MyAPP != nil && MyAPP.count != 0)
    {
        [groupData addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"我管理的群",@"name",MyAPP,@"group", nil]];
    }
    
    if (NoMyAPP != nil && NoMyAPP.count != 0)
    {
        [groupData addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"我加入的群",@"name",NoMyAPP,@"group", nil]];
    }
    
    [_tabGroup reloadData];
}

-(void) refreshChatTableView
{
    chatData  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Chat' and operate='U' "]];
    
    [_tabGroup reloadData];
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView.tag == GCHATTYPE_MY)
    {
        return groupData.count;
    }
    
    return 1;
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(tableView.tag == GCHATTYPE_MY)
        return 25;
    return 0.1;
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

/*
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag == GCHATTYPE_MY)
    {
        NSArray *listarr= [[groupData objectAtIndex:section]objectForKey:@"group"];
        return  listarr.count;
    }
    else if (tableView.tag == GCHATTYPE_CHAT)
        return chatData.count;
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if(tableView.tag == GCHATTYPE_MY)
        return   [[groupData objectAtIndex:section] objectForKey:@"name"];
    
    return @"";
}

/*
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        
        castView.contentView.backgroundColor = [UIColor colorWithWhite:0.875 alpha:1.000];
    }
}
*/

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * CellIdentifier = @"GroupTableViewCell";
    GroupTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        cell.imgtopstraint.constant = 7;
        cell.imgbotmstraint.constant = 7;
        cell.imgHead.layer.masksToBounds = YES;
        cell.imgHead.layer.cornerRadius = 17;
    }
    
    if(tableView.tag == GCHATTYPE_MY)
    {
        Contact *group  =  [[[groupData objectAtIndex:indexPath.section] objectForKey:@"group"] objectAtIndex:indexPath.row];
        cell.labTitle.text = group.mNAME;
        
        NSURL *url= [NSURL URLWithString: [group.mHEAD_IMG hasPrefix:@"http"]?group.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,group.mHEAD_IMG]];
        [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"group"]];
    }
    else if (tableView.tag == GCHATTYPE_CHAT)
    {
        Contact *group  =  [chatData objectAtIndex:indexPath.row];
        cell.labTitle.text = group.mNAME;
        
        NSURL *url = [NSURL URLWithString:group.mHEAD_IMG];
        [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"chat"]];
    }
    return  cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(tableView.tag == GCHATTYPE_MY)
    {
        Contact *group =  [[[groupData objectAtIndex:indexPath.section] objectForKey:@"group"]  objectAtIndex:indexPath.row];
        MessageViewController * message = [[MessageViewController alloc]init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2G,@"messtype":@"1",@"record_DB_ID":group.mPK_ID,
                               @"recordID":group.mID};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
        return;
    }
    if(tableView.tag == GCHATTYPE_CHAT)
    {
        NSLog(@"讨论组");
        Contact *group =  [chatData  objectAtIndex:indexPath.row];
        MessageViewController * message = [[MessageViewController alloc]init];
        NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2G,@"messtype":@"1",@"record_DB_ID":group.mPK_ID,
                               @"recordID":group.mID};
        message.sessInfo = dicc;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
        return;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

//返回上一级页面（这里重写btnBack 目的是为了刷新通讯录中tabbar索引）
- (void)btnBack {
    kAppDelegate.needRefrsh = YES;
    [super btnBack];
}

- (void)viewWillAppear:(BOOL)animated
{
    //如果是讨论组
    if([_GChatType isEqualToString:@"4"])
    {
        [self refreshChatTableView];
    }
    else
    {
        [self refreshTableView];
    }
}

@end
